package logic

import (
	"context"
	"fmt"
	"googee/common/errorx"
	"googee/service/task/model"

	"github.com/zeromicro/go-zero/core/stores/sqlx"
)

func getTaskCountMap(sqlConn sqlx.SqlConn, ctx context.Context, groupId int64, batchId1, batchId0, userId int64) (map[string]int64, error) {
	var task_complete []*X

	//计算最近2次的完成的进度和相关的个数
	sql := "select a.task_id,b.count,a.task_cond_name as cond_name,b.batch_id as batch_id from task_condition a left  join task_progress b on  b.`group_id`=a.`group_id` and a.`task_cond_name`=b.`task_cond_name` where b.`group_id`=? and b.`user_id`=? and (b.`batch_id`=? or b.`batch_id`=?) order by b.`batch_id` asc"
	err := sqlConn.QueryRowsPartialCtx(ctx, &task_complete, sql, groupId, userId, batchId1, batchId0)

	switch err {
	case sqlx.ErrNotFound:
		break
	case nil:
		break
	default:
		return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, fmt.Sprintf("errx :%v", err.Error()))
	}

	task_count_map := make(map[string]int64)
	for _, cond := range task_complete {
		task_count_map[fmt.Sprintf("%v-%v-%v", cond.TaskId, cond.BatchId, cond.CondName)] = cond.Count
	}

	return task_count_map, nil
}

func getOneTaskCountMap(sqlConn sqlx.SqlConn, ctx context.Context, groupId int64, taskId, batchId1, batchId0, userId int64) (map[string]int64, error) {
	var task_complete []*X

	//计算最近2次的完成的进度和相关的个数
	sql := "select a.task_id,b.count,a.task_cond_name as cond_name,b.batch_id as batch_id from task_condition a left  join task_progress b on  b.`group_id`=a.`group_id` and a.`task_cond_name`=b.`task_cond_name` where a.`task_id`=? and b.`group_id`=? and b.`user_id`=? and (b.`batch_id`=? or b.`batch_id`=?) order by b.`batch_id` asc"
	err := sqlConn.QueryRowsPartialCtx(ctx, &task_complete, sql, taskId, groupId, userId, batchId1, batchId0)

	switch err {
	case sqlx.ErrNotFound:
		break
	case nil:
		break
	default:
		return nil, errorx.NewCodeError(errorx.INTERNAL_ERROR, fmt.Sprintf("errx :%v", err.Error()))
	}

	task_count_map := make(map[string]int64)
	for _, cond := range task_complete {
		task_count_map[fmt.Sprintf("%v-%v-%v", cond.TaskId, cond.BatchId, cond.CondName)] = cond.Count
	}

	return task_count_map, nil
}

func isComplete(taskId int64, batchId int64, countMap map[string]int64, condConf map[int64]*model.TaskCondition) bool {
	complete := true

	for k, v := range condConf {
		if k == taskId {
			x := fmt.Sprintf("%v-%v-%v", v.TaskId, batchId, v.TaskCondName)
			if count, ok := countMap[x]; !ok || count < v.Count {
				complete = false
				break
			}
		}
	}

	return complete
}
